<script lang="ts" setup>
import type { VxeGridProps } from '#/adapter';

import { ref, reactive, onMounted, h, watch } from 'vue';
import { Input, Button, Switch, Modal, Form, Select, InputNumber, Divider, Popconfirm, Radio } from 'ant-design-vue';
import { PlusOutlined, ReloadOutlined } from '@ant-design/icons-vue';
import { message } from 'ant-design-vue';
import { Page } from '@vben/common-ui';
import { useVbenVxeGrid } from '#/adapter';

import {
  getRulesApi,
  saveRuleApi,
  deleteRuleApi,
  updateRuleStatusApi,
  type IpSecurityRule,
  type RuleType,
} from '#/api/core/access';

defineOptions({
  name: 'AccessConfig',
});

// 页面状态
const activeTab = ref('blacklist');
const searchText = ref('');
const modalVisible = ref(false);
const modalTitle = ref('添加规则');
const modalLoading = ref(false);
const isEdit = ref(false);
const refreshLoading = ref(false);

// 表格配置
const gridOptions: VxeGridProps<IpSecurityRule> = {
  border: true,
  height: 700,
  keepSource: true,
  rowConfig: {
    keyField: 'id',
  },
  columnConfig: {
    resizable: true,
  },
  pagerConfig: {
    pageSize: 10,
  },
  columns: [
    {
      field: 'name',
      title: '规则名称',
      width: 200,
    },
    {
      field: 'ipPattern',
      title: 'IP模式',
      width: 180,
    },
    {
      field: 'targetType',
      title: '目标类型',
      width: 120,
      slots: {
        default: ({ row }) => {
          const typeMap = {
            GLOBAL: '全局',
            API: 'API',
            USER: '用户',
          };
          return typeMap[row.targetType] || row.targetType;
        },
      },
    },
    {
      field: 'targetValue',
      title: '目标值',
      width: 150,
    },
    {
      field: 'description',
      title: '描述',
      showOverflow: true,
    },
    {
      field: 'enabled',
      title: '状态',
      width: 100,
      slots: {
        default: ({ row }) => {
          return h(Switch, {
            checked: !!row.enabled,
            onChange: (checked: any) => handleStatusChange(row.id, !!checked)
          });
        },
      },
    },
    {
      field: 'operate',
      title: '操作',
      width: 150,
      fixed: 'right',
      slots: {
        default: ({ row }) => {
          return h('div', { class: 'table-actions' }, [
            h('a', { onClick: () => handleEdit(row) }, '编辑'),
            h(Divider, { type: 'vertical' }),
            h(Popconfirm, {
              title: '确定要删除此规则吗？',
              'ok-text': '确定',
              'cancel-text': '取消',
              onConfirm: () => handleDelete(row.id)
            }, {
              default: () => h('a', { class: 'text-error' }, '删除')
            })
          ]);
        },
      },
    },
  ],
  proxyConfig: {
    autoLoad: true,
    ajax: {
      query: async ({ page }) => {
        try {
          const params = {
            page: page.currentPage,
            pageSize: page.pageSize,
            ruleType: (activeTab.value === 'blacklist' ? 'BLACKLIST' : 
                      activeTab.value === 'whitelist' ? 'WHITELIST' : 'RATE_LIMIT') as RuleType,
          };          
          return await getRulesApi(params);
        } catch (error) {
          console.error('加载数据失败:', error);
          message.error('加载数据失败');
          return { items: [], total: 0 };
        }
      },
    },
    props: {
      result: 'items',
      total: 'total',
    },
  },
};

// 根据当前标签页动态设置表格列
watch(activeTab, (newValue) => {
  console.log('标签切换到:', newValue);
  if (newValue === 'ratelimit') {
    gridOptions.columns = [
      ...gridOptions.columns!.slice(0, 5),
      {
        field: 'maxRequestsPerMinute',
        title: '每分钟限制',
        width: 120,
      },
      {
        field: 'maxRequestsPerHour',
        title: '每小时限制',
        width: 120,
      },
      {
        field: 'maxRequestsPerDay',
        title: '每天限制',
        width: 120,
      },
      ...gridOptions.columns!.slice(5),
    ];
  } else {
    // 恢复原始列配置
    gridOptions.columns = gridOptions.columns!.filter(col => 
      !['maxRequestsPerMinute', 'maxRequestsPerHour', 'maxRequestsPerDay'].includes(col.field as string)
    );
  }
  reload();
});

// 使用vben框架的VxeGrid
const [Grid, gridApi] = useVbenVxeGrid({ gridOptions });

// 加载数据的方法
const reload = () => {
  gridApi.reload();
};

// 表单数据
const formState = reactive<any>({
  id: undefined,
  name: '',
  ipPattern: '',
  ruleType: 'BLACKLIST',
  targetType: 'GLOBAL',
  targetValue: '',
  description: '',
  action: 'DENY',
  enabled: true,
  maxRequestsPerMinute: null,
  maxRequestsPerHour: null,
  maxRequestsPerDay: null,
});

// 表单规则 - 使用any类型暂时绕过类型检查
const formRules: any = {
  name: [{ required: true, message: '请输入规则名称', trigger: 'blur' }],
  ipPattern: [{ required: true, message: '请输入IP模式', trigger: 'blur' }],
  ruleType: [{ required: true, message: '请选择规则类型', trigger: 'change' }],
  targetType: [{ required: true, message: '请选择目标类型', trigger: 'change' }],
  action: [{ required: true, message: '请选择动作', trigger: 'change' }],
};



// 刷新数据
const refreshData = async () => {
  refreshLoading.value = true;
  try {
    await reload();
    message.success('数据刷新成功');
  } catch (error) {
    console.error('刷新数据失败:', error);
  } finally {
    refreshLoading.value = false;
  }
};

// 添加规则
const handleAdd = (ruleType: RuleType) => {
  isEdit.value = false;
  modalTitle.value = '添加规则';
  resetForm();
  formState.ruleType = ruleType;
  modalVisible.value = true;
};

// 编辑规则
const handleEdit = (record: IpSecurityRule) => {
  isEdit.value = true;
  modalTitle.value = '编辑规则';
  
  Object.keys(formState).forEach(key => {
    if (key in record) {
      (formState as any)[key] = (record as any)[key];
    }
  });
  
  modalVisible.value = true;
};

// 删除规则
const handleDelete = async (id: number) => {
  try {
    await deleteRuleApi(id);
    message.success('删除成功');
    reload();
  } catch (error) {
    console.error('删除规则失败:', error);
    message.error('删除规则失败');
  }
};

// 更改规则状态
const handleStatusChange = async (id: number, enabled: boolean) => {
  try {
    await updateRuleStatusApi(id, enabled);
    message.success(`${enabled ? '启用' : '禁用'}成功`);
    reload();
  } catch (error) {
    console.error('更新规则状态失败:', error);
    message.error('更新规则状态失败');
  }
};

// 保存规则
const handleSave = async () => {
  modalLoading.value = true;
  try {
    await saveRuleApi(formState);
    message.success('保存成功');
    modalVisible.value = false;
    reload();
  } catch (error) {
    console.error('保存规则失败:', error);
    message.error('保存规则失败');
  } finally {
    modalLoading.value = false;
  }
};

// 重置表单
const resetForm = () => {
  formState.id = undefined;
  formState.name = '';
  formState.ipPattern = '';
  formState.targetType = 'GLOBAL';
  formState.targetValue = '';
  formState.description = '';
  formState.action = 'DENY';
  formState.enabled = true;
  formState.maxRequestsPerMinute = undefined;
  formState.maxRequestsPerHour = undefined;
  formState.maxRequestsPerDay = undefined;
};

// 取消添加/编辑
const handleCancel = () => {
  modalVisible.value = false;
  resetForm();
};

// 初始化
onMounted(() => {
  reload();
});
</script>

<template>
  <Page auto-content-height class="full-width-page">
    <!-- 顶部操作栏 -->
    <div class="access-config-toolbar">
      <div class="toolbar-tabs">
        <Radio.Group v-model:value="activeTab" button-style="solid">
          <Radio.Button value="blacklist">
            <span class="tab-icon">⛔</span> 黑名单
          </Radio.Button>
          <Radio.Button value="whitelist">
            <span class="tab-icon">✅</span> 白名单
          </Radio.Button>
          <Radio.Button value="ratelimit">
            <span class="tab-icon">⏱️</span> 访问频率
          </Radio.Button>
        </Radio.Group>
      </div>
    </div>

    <!-- 使用VxeGrid组件 -->
    <Grid class="wide-grid">
      <template #toolbar-tools>
        <Input.Search
          v-model:value="searchText"
          placeholder="搜索规则名称或IP"
          style="width: 250px"
          allow-clear
          @search="reload"
        />
      </template>
      <template #toolbar-actions>
        <Button
          type="primary"
          @click="handleAdd(activeTab === 'blacklist' ? 'BLACKLIST' : activeTab === 'whitelist' ? 'WHITELIST' : 'RATE_LIMIT')"
        >
          <template #icon><PlusOutlined /></template>
          添加规则
        </Button>
        <Button
          @click="refreshData"
          :loading="refreshLoading"
        >
          <template #icon><ReloadOutlined /></template>
          刷新
        </Button>
      </template>
      <template #empty>
        <div class="empty-placeholder">
          <div class="empty-icon">📋</div>
          <div class="empty-text">
            {{ 
              activeTab === 'blacklist' ? '暂无黑名单规则' : 
              activeTab === 'whitelist' ? '暂无白名单规则' : 
              '暂无访问频率限制规则' 
            }}
          </div>
         
        </div>
      </template>
    </Grid>
    <!-- 添加/编辑规则弹窗 -->
    <Modal
      v-model:visible="modalVisible"
      :title="modalTitle"
      :confirm-loading="modalLoading"
      @ok="handleSave"
      @cancel="handleCancel"
      width="700px"
    >
      <Form :model="formState" :rules="formRules" layout="vertical">
        <Form.Item label="规则名称" name="name" required>
          <Input v-model:value="formState.name" placeholder="请输入规则名称" />
        </Form.Item>
        
        <Form.Item label="IP模式" name="ipPattern" required>
          <Input v-model:value="formState.ipPattern" placeholder="单个IP、IP段或CIDR格式" />
        </Form.Item>

        <div class="form-row">
          <Form.Item label="规则类型" name="ruleType" required>
            <Select v-model:value="formState.ruleType" disabled>
              <Select.Option value="BLACKLIST">黑名单</Select.Option>
              <Select.Option value="WHITELIST">白名单</Select.Option>
              <Select.Option value="RATE_LIMIT">频率限制</Select.Option>
            </Select>
          </Form.Item>
          
          <Form.Item label="目标类型" name="targetType" required>
            <Select v-model:value="formState.targetType">
              <Select.Option value="GLOBAL">全局</Select.Option>
              <Select.Option value="API">API</Select.Option>
              <Select.Option value="USER">用户</Select.Option>
            </Select>
          </Form.Item>
          
          <Form.Item label="动作" name="action" required>
            <Select v-model:value="formState.action">
              <Select.Option value="ALLOW">允许</Select.Option>
              <Select.Option value="DENY">拒绝</Select.Option>
              <Select.Option value="BLOCK">阻止</Select.Option>
            </Select>
          </Form.Item>
        </div>

        <Form.Item v-if="formState.targetType !== 'GLOBAL'" label="目标值" name="targetValue">
          <Input 
            v-model:value="formState.targetValue" 
            :placeholder="formState.targetType === 'API' ? '输入API路径，如/api/user' : '输入用户名'" 
          />
        </Form.Item>

        <div v-if="formState.ruleType === 'RATE_LIMIT'" class="form-row">
          <Form.Item label="每分钟最大请求数" name="maxRequestsPerMinute">
            <InputNumber v-model:value="formState.maxRequestsPerMinute" :min="1" style="width: 100%" :precision="0" />
          </Form.Item>
          
          <Form.Item label="每小时最大请求数" name="maxRequestsPerHour">
            <InputNumber v-model:value="formState.maxRequestsPerHour" :min="1" style="width: 100%" :precision="0" />
          </Form.Item>
          
          <Form.Item label="每天最大请求数" name="maxRequestsPerDay">
            <InputNumber v-model:value="formState.maxRequestsPerDay" :min="1" style="width: 100%" :precision="0" />
          </Form.Item>
        </div>

        <Form.Item label="描述" name="description">
          <Input.TextArea v-model:value="formState.description" placeholder="请输入规则描述" :rows="3" />
        </Form.Item>

        <Form.Item label="状态" name="enabled">
          <Switch v-model:checked="formState.enabled" />
          <span class="form-item-hint">{{ formState.enabled ? '启用' : '禁用' }}</span>
        </Form.Item>
      </Form>
    </Modal>
  </Page>
</template>

<style>
/* 全局样式覆盖 - 使用更强大的选择器 */
.system-config-container .config-drawer-content .config-tabs-content .config-tab-pane {
  max-width: 100% !important;
  padding: 0 10px !important;
}
</style>

<style scoped>
.access-config-container {
  padding: 1.5rem 0;
}

.access-config-header {
  margin-bottom: 1.5rem;
}

.access-config-title {
  font-size: 1.25rem;
  font-weight: 600;
  margin-bottom: 0.5rem;
  color: hsl(var(--foreground));
}

.access-config-desc {
  font-size: 0.875rem;
  color: hsl(var(--muted-foreground));
}

.config-block {
  margin-bottom: 2rem;
  padding: 1.5rem;
  background-color: hsl(var(--popover));
  border-radius: 0.5rem;
  border: 1px solid hsl(var(--border));
  min-height: 500px;
}

.access-config-toolbar {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-bottom: 1.5rem;
  flex-wrap: wrap;
  gap: 1rem;
}

.toolbar-tabs {
  display: flex;
  justify-content: center;
  width: 100%;
}

.toolbar-actions {
  display: flex;
  gap: 0.75rem;
}

.tab-icon {
  margin-right: 0.25rem;
}

.table-actions {
  display: flex;
  align-items: center;
}

.text-error {
  color: hsl(var(--destructive));
}

.empty-placeholder {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 2rem;
}

.empty-icon {
  font-size: 2.5rem;
  margin-bottom: 1rem;
  opacity: 0.5;
}

.empty-text {
  font-size: 1rem;
  color: hsl(var(--muted-foreground));
  margin-bottom: 1rem;
}

.form-item-hint {
  margin-left: 0.5rem;
  color: hsl(var(--muted-foreground));
  font-size: 0.875rem;
}

.form-row {
  display: flex;
  gap: 1rem;
  margin-bottom: 1rem;
}

.form-row :deep(.ant-form-item) {
  flex: 1;
  margin-bottom: 0;
}

.debug-info {
  margin-bottom: 10px;
  padding: 10px;
  background-color: #f0f0f0;
  border-radius: 4px;
  overflow: auto;
  max-height: 200px;
  display: none; /* 隐藏调试信息 */
}

:deep(.ant-btn-primary) {
  background-color: hsl(var(--primary));
  border-color: hsl(var(--primary));
  color: hsl(var(--primary-foreground));
}

:deep(.ant-btn-primary:hover) {
  background-color: hsl(var(--primary) / 0.9);
  border-color: hsl(var(--primary) / 0.9);
}

:deep(.ant-btn-default) {
  background-color: hsl(var(--background));
  border-color: hsl(var(--border));
  color: hsl(var(--foreground));
}

:deep(.ant-btn-default:hover) {
  background-color: hsl(var(--accent));
  border-color: hsl(var(--accent-foreground));
  color: hsl(var(--accent-foreground));
}

/* 宽表格样式 - 使用更强力的选择器 */
:deep(.vxe-grid) {
  width: 100% !important;
  max-width: none !important;
  margin: 0 10px !important;
}

:deep(.vxe-table--main-wrapper),
:deep(.vxe-table--body-wrapper),
:deep(.vxe-table),
:deep(.vxe-table--body) {
  width: 100% !important;
  max-width: none !important;
}

/* 全宽页面样式 */
.full-width-page {
  max-width: 100% !important;
  padding: 0 10px !important;
}

:deep(.full-width-page .vben-page-content) {
  max-width: 100% !important;
  padding: 0 !important;
}

:deep(.vxe-table) {
  width: 100% !important;
}

:deep(.vxe-table--body) {
  width: 100% !important;
}
</style>